/* ============================================================================= */
/*                   TABLE 10 - ACCEPTED VS REJECTED                             */
/* ============================================================================= */

clear all

/* ============================================================================= */
/*                   STEP 1: PREPARE WEIGHTED SAMPLES FOR MATCHING               */
/* ============================================================================= */

/* Load matched sample weights for rejected firms */
use "$output\rejected_psm.dta", clear
keep siren weight
sort siren weight
bys siren weight: gen nb = _n  // Identify unique firms
keep if nb == 1  // Keep only the first occurrence
drop nb
save "$output\rejected_matched_SIREN_weight.dta", replace

/* ============================================================================= */
/*                 STEP 2: LOAD AND CLEAN CIPE DEFAULT DATA (REJECTED)           */
/* ============================================================================= */

/* Import CIPE data for rejected firms */
import delimited "$input\CIPE_SIREN_defaulters_mdate_rejected.csv", clear

/* Convert date formats */
gen time = date(date, "YMD")
gen qdate = qofd(time)  // Convert to quarterly date format
format time %td
format qdate %tq

/* Reclassify industry groups */
replace industry = "public" if inlist(industry, "P", "Q", "R", "S")  // Merge public sector
replace industry = "DE" if inlist(industry, "D", "E")  // Merge manufacturing industries
replace industry = "FL" if inlist(industry, "F", "L")  // Merge construction & real estate

/* Remove industries with insufficient observations */
drop if inlist(industry, "A", "K", "O", "B", "DE", "0000Z")

/* Create grouped industry variable */
egen industry10 = group(industry)

/* ============================================================================= */
/*                  STEP 3: STANDARDIZE RATINGS FOR ANALYSIS                     */
/* ============================================================================= */

/* Normalize ratings (converting different formats into a unified scale) */
replace rating = "3A" if rating == "3++"
replace rating = "3B" if rating == "3+"
replace rating = "3C" if rating == "3"
replace rating = "4A" if rating == "4+"
replace rating = "4B" if rating == "4"
replace rating = "5A" if rating == "5+"
replace rating = "5B" if rating == "5"

/* Convert rating to numerical values */
encode rating, gen(ratinge)
replace ratinge = ratinge - 1
replace ratinge = 13 if ratinge == 0  // Assign a special value for missing ratings

/* Keep only relevant time period */
keep if inrange(qdate, qofd(date("20140101","YMD")), qofd(date("20191231","YMD")))

/* ============================================================================= */
/*              STEP 4: MERGE CIPE LOAN DATA AND CREATE EVENT TIME               */
/* ============================================================================= */

preserve
keep siren ifploan qdate accepted justrejected
keep if ifploan > 0 | justrejected == 1  // Keep firms that either received a loan or were just rejected
rename qdate qdateloan  // Rename loan date variable
keep siren qdateloan
sort siren qdateloan
quietly by siren: gen dup = cond(_N==1, 0, _n)  // Identify duplicates
drop if dup > 1  // Keep only the first loan occurrence per firm
keep siren qdateloan
save "$output\CIPE_PCL_reject_mdateloan.dta", replace
restore

/* Merge with main dataset to get loan dates */
merge m:1 siren using "$output\CIPE_PCL_reject_mdateloan.dta"
keep if _merge == 1 | _merge == 3  // Keep firms with loan data
drop _merge

/* Start logging */
capture log close
log using "$logs\CIPE_and_PCL_rejected.log", replace

/* ============================================================================= */
/*              STEP 5: DEFINE EVENT TIME FOR DIFFERENCE-IN-DIFFERENCES          */
/* ============================================================================= */

/* Compute time difference (years) since the loan was granted */
gen delta_year = yofd(dofq(qdate)) - yofd(dofq(qdateloan))
keep if inrange(delta_year, -4, 4)  // Keep only observations within -4 to +4 years

/* Identify unrated firms before loan */
preserve
keep if qdate == qdateloan - 1
gen unrated_pre = ratinge == 13
keep siren unrated_pre
save "$output\unrated_siren.dta", replace
restore

/* Merge unrated firm indicator */
merge m:1 siren using "$output\unrated_siren.dta", nogen keep(3)

/* Define post-loan period */
gen post = qdateloan < qdate

/* Create firm-level fixed effects */
egen nesc = group(industry)
tsset siren qdate, quarterly

/* ============================================================================= */
/*               STEP 6: MERGE MATCHED SAMPLE WEIGHTS FOR REJECTED FIRMS         */
/* ============================================================================= */

merge m:1 siren using "$output\rejected_matched_SIREN_weight.dta"
keep if _merge == 3
drop _merge

/* ============================================================================= */
/*               STEP 7: DEFINE DEPENDENT VARIABLES FOR DEFAULT ANALYSIS         */
/* ============================================================================= */

/* Define firm defaults as bankruptcy (pclliquidate) or closure (pclopen) */
gen dead = pclliquidate | pclopen
replace dead = 0 if dead == .

/* ============================================================================= */
/*               STEP 8: RUN REGRESSIONS - DEFAULT RISK AND RATINGS              */
/* ============================================================================= */

/* Firm-level default regression */
capture estimates drop *
eststo reg1: reghdfe dead i1.accepted##i1.post [pweight=weight], a(i.siren i.nesc#i.qdate) cluster(siren) 
estadd local firm "Y", replace 
estadd local indyear "Y", replace  

/* Firm rating regression */
eststo reg2: reghdfe ratinge i1.accepted##i1.post [pweight=weight] if ratinge != 13, a(i.siren i.nesc#i.qdate) cluster(siren) 
estadd local firm "Y", replace 
estadd local indyear "Y", replace 

/* ============================================================================= */
/*               STEP 9: EXPORT RESULTS TO LATEX TABLE                           */
/* ============================================================================= */

* Export Table 10 col 4
esttab reg1 using "$tables\Table_7_firm_level_defaults_matched_rejected.tex", replace ///
    noomitted nobase fragment gap booktabs label nonote noobs nolines /// 
    b(%9.3f) drop(_cons) se(%9.3f) star(* 0.10 ** 0.05 *** 0.01) posthead(\midrule) ///
    mtitles("$\mathbbm{1}$(Default)" "Rating" "$\mathbbm{1}$(Rated)") ///
    order(1.accepted#1.post  1.post) varlabel(1.post "Post" 1.accepted#1.post `"Accepted $\times$ Post"' ) ///
    stats(firm indyear N r2, label(`"Firm FE"' `"Industry-Year FE"' `"\midrule N"' `"R-sq"') ///
    layout("\multicolumn{1}c{@}") fmt(%9.0fc %9.0fc %9.0fc %9.2f  ) ) 

* Export IA Table G1 col 4	
esttab reg2 using "$tables\Table_7_firm_level_ratings_matched_rejected.tex", replace ///
    noomitted nobase fragment gap booktabs label nonote noobs nolines /// 
    b(%9.3f) drop(_cons) se(%9.3f) star(* 0.10 ** 0.05 *** 0.01) posthead(\midrule) ///
    mtitles("$\mathbbm{1}$(Default)" "Rating" "$\mathbbm{1}$(Rated)") ///
    order(1.accepted#1.post  1.post) varlabel(1.post "Post" 1.accepted#1.post `"Accepted $\times$ Post"' ) ///
    stats(firm indyear N r2, label(`"Firm FE"' `"Industry-Year FE"' `"\midrule N"' `"R-sq"') ///
    layout("\multicolumn{1}c{@}") fmt(%9.0fc %9.0fc %9.0fc %9.2f  ) ) 
	
	
/* Close log file */
log close
